package com.wfm;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

public class App {
    Entry entry = null;
    public static void main(String[] args) {
        App app = new App();
        while (true){
            System.out.println(app.test());
        }
    }
    public String test(){
        initFlowRules();
        try {
            entry= SphU.entry("test1");
            Thread.sleep(60L);
            return "a";
        } catch (BlockException e) {
            System.out.println("BlockException");
            return "BlockException";
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(entry!=null){
                entry.exit();
            }
            ContextUtil.exit();
        }
    }

    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("test1");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(10);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
